package com.t282.crm.service.impl;

import com.t282.crm.entity.Right;
import com.t282.crm.entity.Role;
import com.t282.crm.entity.User;
import com.t282.crm.repository.RightRepository;
import com.t282.crm.repository.RoleRepository;
import com.t282.crm.service.RoleService;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleRepository roleRepository;
    @Resource
    private RightRepository rightRepository;

    @Override
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    @Override
    public List<Right> findAllRights() {
        return rightRepository.findAll();
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightRepository.findRightsByRolesOrderByRightCode(role);
    }

    @Override
    public Role saveRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRoleById(Long roleId) {
        roleRepository.deleteById(roleId);
    }

    @Override
    public void deleteRole(Role role) {
        roleRepository.delete(role);
    }

    @Override
    public Role getRole(Long roleId) {
        return roleRepository.findById(roleId).get();
    }

    @Override
    public Page<Role> findRole(String roleName, Pageable pageable) {
        return roleRepository.findROlesByRoleNameLike("%"+roleName+"%",pageable);
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleRepository.findRoleByUsers(user);
    }

    @Override
    public Map<String, String> loadFilterChainDefinitions() {
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();   //必须使用LinkedHashMap（有序集合）
        //配置可以匿名访问的资源（URL）：静态资源
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/images/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/localcss/**","anon");
        filterChainDefinitionMap.put("/localjs/**","anon");

        filterChainDefinitionMap.put("/user/doLogin","anon");
        filterChainDefinitionMap.put("/user/logOut","logout");   //注销过滤器，自动注销

        //配置需要特定权限才能访问的资源（URL）
        //静态授权：包括全部需要特定权限才能访问的资源（URL）
        //filterChainDefinitionMap.put("/user/list","perms[用户列表]");
        //filterChainDefinitionMap.put("/user/add","perms[用户添加]");
        //filterChainDefinitionMap.put("/user/edit","perms[用户编辑]");
        //filterChainDefinitionMap.put("/user/del","perms[用户删除]");

        //动态授权
        List<Right> rights = findAllRights();
        for (Right right : rights) {
            if(right.getRightUrl() != null && !right.getRightUrl().trim().equals("")){
                filterChainDefinitionMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }

        //配置认证访问：其他资源（URL）必须认证通过才能访问
        filterChainDefinitionMap.put("/**","authc");    //必须放在过滤器链的最后面

        return filterChainDefinitionMap;
    }

    @Override
    public void reloadFilterChainDefinitions() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");
            synchronized (shiroFilter){
                //获取过滤器管理器
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                //清空初始权限配置
                manager.getFilterChains().clear();
                //重新加载动态权限，配置权限验证规则
                Map<String,String> chains = loadFilterChainDefinitions();
                for (Map.Entry<String,String> entry:chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" ","");
                    manager.createChain(url,chainDefinition);
                }
                System.out.println("更新权限成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
